<template>
  <div class="app-container">
    <realAdd ref="realForm" @status="realStatus" />
    <div class="filter-container">
      <el-input v-model="query.blurry" placeholder="搜索内容" style="width: 200px;" class="filter-item" />
      <el-date-picker
        v-model="query.create_time"
        :default-time="['00:00:00','23:59:59']"
        type="daterange"
        range-separator=":"
        class="filter-item"
        value-format="yyyy-MM-dd HH:mm:ss"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width:230px"
        unlink-panels
        :picker-options="queryPickerOptions"
      />
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="handleQuery()">搜索</el-button>
      <el-button class="filter-item" type="warning" icon="el-icon-refresh-left" @click="resetQuery()">重置</el-button>
    </div>
    <div class="filter-container" style="display: flex;justify-content: space-between;">
      <el-button-group>
        <!-- <el-button v-permission="['admin', permName + ':add']" class="filter-item" type="primary" icon="el-icon-plus" @click="addRealName()">新增</el-button>
        <el-button class="filter-item" :disabled="batchStatus" type="success" icon="el-icon-edit" @click="editRealName()">修改</el-button> -->
        <el-button v-permission="['admin', permName + ':delete']" class="filter-item" :disabled="!batchStatus" type="danger" icon="el-icon-delete" @click="formBatchDel()">删除</el-button>
        <el-button class="filter-item" :loading="downloadLoading" type="warning" icon="el-icon-download" @click="handleExportExcel()">导出</el-button>
      </el-button-group>
      <el-button-group>
        <!-- <el-button class="filter-item" size="mini" plain type="info" icon="el-icon-search" /> -->
        <el-button class="filter-item" size="mini" icon="el-icon-refresh" @click="refresh()" />
      </el-button-group>
    </div>
    <!--表单渲染-->
    <el-dialog :visible.sync="formVisible" append-to-body :close-on-click-modal="false" title="实名审核" width="500px">
      <el-form ref="form" :rules="rules" :model="form" size="small" label-width="80px">
        <el-form-item label="审核操作" prop="status">
          <el-radio v-model="form.status" :label="3">待审核</el-radio>
          <el-radio v-model="form.status" :label="2">预审核</el-radio>
          <el-radio v-model="form.status" :label="1">通过</el-radio>
          <el-radio v-model="form.status" :label="0">未通过</el-radio>
        </el-form-item>
        <el-form-item label="审核说明" prop="remark">
          <el-input v-model="form.introduction" :rows="4" type="textarea" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submit()">确认</el-button>
      </div>
    </el-dialog>

    <!-- 表格 -->
    <div class="filter-container">
      <el-table
        v-loading="loading"
        :data="listData"
        style="width: 100%"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        header-align="center"
        @selection-change="tabSelectionChange"
        @current-change="handleCurrentFormChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="头像" width="80" align="center">
          <template slot-scope="{row}">
            <el-image style="width: 28px; height: 28px;display: inline-table;" :src="row.avatar" fit="fill" lazy :preview-src-list="[row.avatar,row.id_card_z,row.id_card_f]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="id_card_num" label="身份证号" width="200" />
        <el-table-column prop="phone" label="联系方式" width="120" />
        <el-table-column label="身份证" width="80" align="center">
          <template slot-scope="{row}">
            <el-image style="width: 28px; height: auto;display: inline-table;" :src="row.id_card_z" fit="fill" lazy :preview-src-list="[row.id_card_z,row.id_card_f,row.avatar]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" show-overflow-tooltip label="创建时间" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="80" align="center">
          <template slot-scope="{row}">
            <el-tag :type="SHZT[row.status].type" effect="plain"> {{ SHZT[row.status].label }} </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-permission="['admin', permName + ':audit', permName + ':delete']"
          label="操作"
          class-name="small-padding fixed-width"
          align="center"
          width="160"
        >
          <template slot-scope="{row,$index}">
            <el-tooltip class="item" effect="dark" content="审核" placement="left">
              <el-button v-permission="['admin','real:audit']" type="primary" size="mini" icon="el-icon-s-promotion" style="margin-left: 0;width: auto;" @click="formEdit(row)" />
            </el-tooltip>
            <el-popconfirm v-permission="['admin','real:delete']" title="你确定删除该条数据吗？" icon="el-icon-info" icon-color="red" @onConfirm="handleDelete(row,$index)">
              <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" style="width: auto;" />
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-pagination
      background
      :current-page="currentPage"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      :hide-on-single-page="true"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>
<script>

import { parseTime } from '@/utils'
// 权限判断函数
import checkPermission from '@/utils/permission'
import tableCURD from '@/api/system/real'

import realAdd from '@/components/Real/add'
// 表单字段默认值
const defaultForm = { id: null, status: 1, remark: null }
// 查询字段默认值
const defaultQuery = { blurry: null, create_time: null }

export default {
  name: 'Real',
  components: { realAdd },
  data() {
    return {
      // 角色名称，每次修改这里，最好和上面的name同名。
      permName: 'real',
      // 权限判断函数
      checkPermission,
      // 表数据
      listData: [],
      // 加载状态
      loading: false,
      // 提交数据加载状态
      submitLoading: false,
      // 显示表单
      formVisible: false,
      // 批量操作状态
      batchStatus: false,
      // 选中的数据行
      batchForm: [],
      // 表单字段初始数据
      form: JSON.parse(JSON.stringify(defaultForm)),
      // 数据校验
      rules: {
        status: [{ required: true, message: '请输入用户名', trigger: 'blur' }]
      },
      // 查询字段
      query: JSON.parse(JSON.stringify(defaultQuery)),
      SHZT: {
        3: { type: '', label: '待审核' },
        1: { type: 'success', label: '通过' },
        0: { type: 'danger', label: '未通过' },
        2: { type: 'warning', label: '预审核' }
      },
      // 提交的参数
      parames: {},
      // 查询时间快捷选项
      queryPickerOptions: {
        shortcuts: [
          { text: '最近一周', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 7); picker.$emit('pick', [start, end]) } },
          { text: '最近一个月', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 30); picker.$emit('pick', [start, end]) } },
          { text: '最近三个月', onClick(picker) { const end = new Date(); const start = new Date(); start.setTime(start.getTime() - 3600 * 1000 * 24 * 90); picker.$emit('pick', [start, end]) } }
        ]
      },
      // 每页显示个数选择器的选项设置
      pageSizes: [20, 50, 100, 150, 200],
      // 每页显示条目个数
      pageSize: 20,
      // 当前页
      currentPage: 1,
      // 总条目数
      dataTotal: 0,
      // 导出状态
      downloadLoading: false,
      // 导出文件的文件名
      filename: '',
      // 导出表宽度自动
      fileAutoWidth: true,
      // 导出文件类型 xlsx,txt,csv
      fileBookType: 'xlsx'
    }
  },
  created() {
    // 页面加载时判断 api 权限，有权限再请求
    if (checkPermission(['admin', this.permName + ':list'])) {
      this.getList(this.currentPage, this.pageSize)
    }
    this.filename = this.$route.meta.title
  },
  methods: {
    // 初始化表单
    formInit(formName, data) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      const d = JSON.parse(JSON.stringify(data))
      this.form = { id: d.id, status: d.status, remark: d.remark }
      console.log('data', this.form)
      // 显示表单
      this.formVisible = true
      return true
    },
    // 获取数据列表
    getList() {
      const that = this
      this.loading = true
      tableCURD.list({
        limit: that.pageSize,
        page: that.currentPage,
        ...this.parames
      }).then(res => {
        if (res.code === 0) {
          that.listData = res.data
          that.currentPage = res.page.currentPage
          that.dataTotal = res.page.total
          that.pageSize = res.page.limit
          this.loading = false
        }
      }).catch(res => {
        this.loading = false
      })
    },
    // 查询
    handleQuery() {
      this.currentPage = 1
      this.parames = this.query
      this.getList()
    },
    // 重置查询
    resetQuery() {
      const that = this
      that.currentPage = 1
      that.query = JSON.parse(JSON.stringify(defaultQuery))
      that.parames = {}
      that.getList()
    },
    // 刷新表单
    refresh() {
      this.getList()
    },
    // 表单编辑
    formEdit(data) {
      if (data) {
        this.formInit('form', data)
      }
    },

    // 删除处理
    handleDelete(row, $index) {
      tableCURD.del({ id: row.id }).then(res => {
        if (res.code === 0) {
          this.$notify({
            title: '操作完成！',
            type: 'success'
          })
          this.refresh()
        }
      })
    },
    // 批量删除
    formBatchDel() {
      const ids = []
      for (var i in this.batchForm) {
        ids.push(this.batchForm[i].id)
      }
      if (ids.length > 0) {
        tableCURD.del({ id: ids }).then(res => {
          if (res.code === 0) {
            this.$notify({
              title: '操作完成！',
              type: 'success'
            })
            this.refresh()
          }
        })
      }
    },
    // cheackbox选中数据行处理
    tabSelectionChange(val) {
      if (val.length > 0) {
        this.batchStatus = true
        this.batchForm = val
      } else {
        this.batchStatus = false
        this.batchForm = []
      }
    },
    // 点击当前行的处理
    handleCurrentFormChange(val) {
      console.log(val)
    },
    // 选择分页数据大小的处理，每页多少条数据
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getList()
    },
    // 选择分页的处理
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },
    /**
     * 提交新增/编辑
     */
    submit() {
      this.$refs['form'].validate((valid) => {
        this.submitLoading = true
        if (valid) {
          tableCURD.audit(this.form).then(res => {
            if (res.code === 0) {
              this.$notify({
                title: '操作成功',
                type: 'success'
              })
              this.refresh()
              this.formVisible = false
            }
            this.submitLoading = false
          }).catch(res => {
            this.submitLoading = false
          })
        } else {
          this.$message({
            message: '数据校验失败',
            type: 'warning'
          })
          this.submitLoading = false
          return false
        }
      })
    },
    handleExportExcel() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        // 表头名
        const tHeader = []
        // 字段
        const filterVal = []
        // 数据集
        const list = this.listData
        // 这里我设置表头名字和字段一样
        for (var key in list[0]) {
          tHeader.push(key)
          filterVal.push(key)
        }
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.fileAutoWidth,
          bookType: this.fileBookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        // 时间处理，时间戳转时间格式
        if (j === 'create_time') {
          if (v[j] === 0) { return '' }
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    addRealName() {
      this.$refs.realForm.handleSubmit = 'add'
      this.$refs.realForm.formVisible = true
    },
    editRealName() {
      this.$refs.realForm.handleSubmit = 'edit'
      this.$refs.realForm.formVisible = true
    },
    // 认证成功后的回调
    realStatus(res) {
      this.$message({
        message: '提交成功',
        type: 'warning'
      })
      this.$refs.realForm.formVisible = false
      this.getList()
    }

  }
}
</script>
